package controllers;

import java.util.HashMap;
import java.util.Map;



import spark.Request;
import spark.Response;
import data.AuthDAO;
import data.IAuthDAO;
import models.*;

public class AuthController extends BaseController {

	private IAuthDAO dao;
	
	public AuthController(Request request, Response response) {
		super(request, response);
		dao = new AuthDAO();
	}
	
	public Object logoff(){
		request.session().removeAttribute("user");
		redirect("/");
		return "";
	}
	
	public Object login(){
		Map<String, Object> attributes = new HashMap<>();
		if(request.requestMethod().toUpperCase().equals("POST")){
			String username = request.queryParams("username").trim();
			String password = request.queryParams("password");
			
			try {
				User user = dao.authenticate(username, password);
				if(user != null && user.getId() > 0) {
					request.session().attribute("user", user);
					redirect(this.getCurrentRequestUrl());
					return "";
				} else {
					attributes.put("error", "Username or password is incorrect");
					return render(attributes, "auth/login.html");
				}
			}catch(Exception e){
				attributes.put("error", e.toString());
				return render(attributes, "auth/login.html");
			}

		} else {
			return render(attributes, "auth/login.html");
		}
	}
	
	
}